RwLock in std::sync 您所在的位置:网站首页 go rwlock RwLock in std::sync

RwLock in std::sync

#RwLock in std::sync| 来源: 网络整理| 查看: 265

A reader-writer lock

This type of lock allows a number of readers or at most one writer at any point in time. The write portion of this lock typically allows modification of the underlying data (exclusive access) and the read portion of this lock typically allows for read-only access (shared access).

In comparison, a Mutex does not distinguish between readers or writers that acquire the lock, therefore blocking any threads waiting for the lock to become available. An RwLock will allow any number of readers to acquire the lock as long as a writer is not holding the lock.

The priority policy of the lock is dependent on the underlying operating system’s implementation, and this type does not guarantee that any particular policy will be used. In particular, a writer which is waiting to acquire the lock in write might or might not block concurrent calls to read, e.g.:

Potential deadlock example // Thread 1 | // Thread 2 let _rg = lock.read(); | | // will block | let _wg = lock.write(); // may deadlock | let _rg = lock.read(); |

The type parameter T represents the data that this lock protects. It is required that T satisfies Send to be shared across threads and Sync to allow concurrent access through readers. The RAII guards returned from the locking methods implement Deref (and DerefMut for the write methods) to allow access to the content of the lock.

Poisoning

An RwLock, like Mutex, will become poisoned on a panic. Note, however, that an RwLock may only be poisoned if a panic occurs while it is locked exclusively (write mode). If a panic occurs in any reader, then the lock will not be poisoned.

Examples use std::sync::RwLock; let lock = RwLock::new(5); // many reader locks can be held at once { let r1 = lock.read().unwrap(); let r2 = lock.read().unwrap(); assert_eq!(*r1, 5); assert_eq!(*r2, 5); } // read locks are dropped at this point // only one write lock may be held, however { let mut w = lock.write().unwrap(); *w += 1; assert_eq!(*w, 6); } // write lock is dropped hereRun


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有